package com.lanou.fooddemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.lanou.fooddemo.R;
import com.lanou.fooddemo.activity.RecommendInformationActivity;
import com.lanou.fooddemo.adapter.RecommendAdapter;
import com.lanou.fooddemo.bean.DataBean;
import com.lanou.fooddemo.bean.DetailBean;
import com.lanou.fooddemo.bean.SubCardsBean;
import com.lanou.fooddemo.external.material_loading_progress_bar.CircleProgressBar;
import com.lanou.fooddemo.external.swipe_refresh_loading_layout.SwipeRefreshLoadingLayout;
import com.lanou.fooddemo.theme.FoodTheme;
import com.lanou.fooddemo.util.CommonUtil;
import com.lanou.fooddemo.util.NetUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by dllo on 2015/8/5.
 */
public class RecommendFragment extends Fragment {

    /**
     * 传递给小详细信息界面的Extra数据key
     */
    public static final String INFORMATION_KEY = "information";


    /**
     *
     * 设置读取中的dialog显示类型值
     */
    private final int TYPE_DIOLOG_SHOW = 1;

    /**
     *
     * 首次拉去数据的Message的类型值
     */
    private final int TYPE_GET_DATA = 2;

    /**
     *
     * 非首次拉去shu数据的Message的类型值
     * */
    private final int TYPE_GET_NEXT_DATA = 3;

    private List<DataBean> dataBeans;
    private RecommendAdapter adapter;

    /**
     * 定义list刷新进度条颜色
     */
    private int[] listColor = {android.R.color.holo_red_light,android.R.color.white,
    android.R.color.holo_red_light,android.R.color.holo_red_light};
    private Handler handler;
    /**
     * 数据ListView
     */
    private ListView listView;
    /**
     * 刷新布局
     */
    private SwipeRefreshLoadingLayout swipeRefreshLoadingLayout;
    /**
     * 读取中Dialkog
     */
    private CircleProgressBar circleProgressBar;
    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,
                             Bundle savedInstanceState){
        //通过LayoutInflater从layout布局中获取布局view
        View view = inflater.inflate(R.layout.fragment_recommend,null);
        //初始化组件
        initView(view);
        getSameCityData(TYPE_GET_DATA);

        return view;
    }




    /**
     * 控件初始化方法
     */

    private void initView(View view){
        listView = (ListView) view.findViewById(R.id.sameCityListView);
        swipeRefreshLoadingLayout =
                (SwipeRefreshLoadingLayout)view.findViewById(R.id.sameCitySwipeLayout);
        circleProgressBar = (CircleProgressBar) view.findViewById(R.id.sameCityProgressBar);
        //设置读取中dialog显示
        circleProgressBar.setVisibility(View.VISIBLE);
        //初始化列表数据
        dataBeans = new ArrayList<DataBean>();
        //初始化列表适配器
        adapter = new RecommendAdapter(getActivity(),dataBeans);
        //为listView绑定适配器
        listView.setAdapter(adapter);
        //为刷新布局添加进度条颜色
        swipeRefreshLoadingLayout.setColor(listColor[0],listColor[1],listColor[2],listColor[3]);
        swipeRefreshLoadingLayout.setOnRefreshListener(new SwipeRefreshLoadingLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取首次拉去数据
                getSameCityData(TYPE_GET_DATA);
            }
        });
        //注册上拉加载更多
        swipeRefreshLoadingLayout.setOnLoadListener(new SwipeRefreshLoadingLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                //加载更多数据
                getSameCityData(TYPE_GET_NEXT_DATA);
            }
        });
        //注册listView按下时监听
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //创建跳转详细信息界面的Activity的Intent
                Intent intent = new Intent(getActivity(), RecommendInformationActivity.class);
                //获取列表相应点击位置的跳转信息
                DetailBean detailBean = dataBeans.get(position).getDetail();
                //将需要条抓的url携带信息传递到详细信息界面
                intent.putExtra(INFORMATION_KEY, detailBean.getApi());
                //跳转到详细信息界面
                startActivity(intent);
            }
        });
        //实例化Handler
        handler = new Handler(new Handler.Callback(){
            @Override
            public boolean handleMessage(Message msg){
                switch (msg.what){
                    case TYPE_DIOLOG_SHOW:
                        circleProgressBar.setVisibility(View.VISIBLE);
                        break;
                    //处理首次进入和下拉舒心的数据更新
                    case TYPE_GET_DATA:
                        //清空dataBeans的List
                        dataBeans.clear();
                        //将msg中的数据全部填充到dataBeans
                        dataBeans.addAll((List<DataBean>) msg.obj);
                        //取消刷新状态
                        swipeRefreshLoadingLayout.setRefreshing(false);
                        circleProgressBar.setVisibility(View.INVISIBLE);
                        break;
                    //处理加载更多的数据更新
                    case TYPE_GET_NEXT_DATA:
                        //将msg中的数据全部填充到dataBeand
                        dataBeans.addAll((List<DataBean>)msg.obj);
                        dataBeans.addAll((List<DataBean>) msg.obj);
                        //取消加载更多状态
                        swipeRefreshLoadingLayout.setLoading(false);
                        circleProgressBar.setVisibility(View.INVISIBLE);
                        break;
                }
                //通知适配器数据改变,更新试图
                adapter.notifyDataSetChanged();
                return true;
            }
        });
        //设置主题
        setTheme();
    }

    @Override
    public void onResume() {
        super.onResume();
        //设置主题
        setTheme();
    }

    /**
     * 获取同城数据
     * @param-url 获取数据的url
     *@param type 拉去 类型,是刷新或首次拉取还是非首次拉去
     */
    private void getSameCityData(int type){
        //实例化自定义Runable接口类SameCityRunable
        SameCityRunable sameCityRunable = new SameCityRunable(type);
            //将Runable实例类放入Thread构造方法,实例化线程
            Thread thread = new Thread(sameCityRunable);
        //开启线程
        thread.start();
    }
    private class SameCityRunable implements Runnable{
        /**
         * 读取中进度条显示消息
         */
        private Message msgDialogShow;
        /**
         * 数据传递消息
         */
        private Message msgData;
        /**
         * 首次拉取或非首次拉去类型
         */
        private int type;
        List<DataBean> runableDataBeanList = null;
        public SameCityRunable(int t){ type = t;}

        @Override
        public void run() {
            //从handler中获取消息赋给进度条显示消息
            msgDialogShow = handler.obtainMessage();
            //设置消息类型what值
            msgDialogShow.what = TYPE_DIOLOG_SHOW;
            //发送进度条显示消息
            handler.sendMessage(msgDialogShow);
            //判断数据拉取类型,从不同接口拉取数据
            if (TYPE_GET_DATA == type){
                runableDataBeanList = NetUtil.getDataBeanListDataForRecomment();
            }else if (TYPE_GET_NEXT_DATA == type){
                runableDataBeanList = NetUtil.getDataBeanListDataForRecommendTitleForNext();
            }
            if (CommonUtil.isListNotNull(runableDataBeanList)){
                //从handler获取消息
                msgData = handler.obtainMessage();
                //设置消息what值
                msgData.what = type;
                //设置消息obj内容值
                msgData.obj = runableDataBeanList;
                Log.d("test",runableDataBeanList.size()+"");
                Log.d("test", runableDataBeanList.get(0).getSubCards() + "");
                for (int i = 0; i < runableDataBeanList.size(); i++) {


                List<SubCardsBean>  lists =  runableDataBeanList.get(i).getSubCards();
                Log.d("test", i + "----->"+lists.get(0).getType());
                Log.d("test", i + "----->"+lists.get(1).getType());
                Log.d("test", i + "----->"+lists.get(2).getType());
                }
                //发送消息给handler
                handler.sendMessage(msgData);
            }
        }
    }

    /**
     * 设置主题
     */
    public void setTheme() {
        listColor[0] = FoodTheme.getLoadingLayoutProcessColor();
        listColor[2] = FoodTheme.getLoadingLayoutProcessColor();
        listColor[3] = FoodTheme.getLoadingLayoutProcessColor();
        swipeRefreshLoadingLayout.setColor(listColor[0], listColor[1],
                listColor[2], listColor[3]);
        circleProgressBar.setColorSchemeResources(new int[]{FoodTheme.getCircleProgressBarColor()});
    }

}
